package com.sphd.emanu.activity.login;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.MainActivity;
import com.sphd.emanu.R;
import com.sphd.emanu.activity.changepwd.ChangePwdActivity;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.permission.Moudle;
import com.sphd.emanu.permission.PermissionInfo;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.PermissionConfig;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGNotifaction;
import com.tencent.android.tpush.XGPushManager;
import com.tencent.android.tpush.XGPushNotifactionCallback;
import com.wzutils.L;
import com.wzutils.MD5Utils;
import com.wzutils.SPUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 登录界面
 *
 * @Author Hu
 * @Time 2017/5/3 -- 15:25.
 * @Email 87683202@qq.com
 */
public class LoginActivity extends MVPBaseActivity<LoginContract.View, LoginPresenter> implements LoginContract.View {

    @BindView(R.id.user_name)
    MaterialEditText userName;
    @BindView(R.id.user_pwd)
    MaterialEditText userPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.forget_pwd)
    TextView btnForget;
    AndroidNextInputs inputs;
    Intent intent;
    Bundle bundle;
    String token = null;
    List<Moudle> perssionList;
    @BindView(R.id.checkbox_rem)
    CheckBox checkboxRem;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initView();
        initXg();

    }

    private void addData(Integer id, boolean lookOver, boolean operation) {
        perssionList.add(new Moudle(id, new PermissionInfo(lookOver, operation)));
    }


    /**
     * 信鸽推送的初始化，可查阅信鸽的文档
     */
    private void initXg() {
        XGPushManager.registerPush(context, new XGIOperateCallback() {
            @Override
            public void onSuccess(Object data, int i) {
                token = String.valueOf(data);
                Toast.makeText(getApplicationContext(), "推送开启成功", Toast.LENGTH_SHORT).show();
                Log.e("TPush", "注册成功，设备token为：" + data);
            }

            @Override
            public void onFail(Object data, int errCode, String msg) {
                Toast.makeText(getApplicationContext(), "注册失败，" + errCode + ",错误信息：" + msg, Toast.LENGTH_LONG).show();
                Log.e("TPush", "注册失败，错误码：" + errCode + ",错误信息：" + msg);
            }
        });

        XGPushManager.setNotifactionCallback(new XGPushNotifactionCallback() {
            @Override
            public void handleNotify(XGNotifaction xgNotifaction) {
                Log.e("test", "处理信鸽通知：");
                L.e(xgNotifaction.toString());
                xgNotifaction.doNotify();
            }
        });
    }

    /**
     * 初始化数据
     */
    private void initView() {
        intent = getIntent();
        //判断是否从更改密码界面过来的 如果是的话就获取传递的账号密码进行填充到对话框
        if (intent.getBooleanExtra(Constant.CHANGE_PWD, false)) {
            SPUtils.remove(context, Constant.LOGIN_NAME);
            SPUtils.remove(context, Constant.LOGIN_PWD);
            userName.setText(intent.getStringExtra(Constant.LOGIN_NAME));
            userPwd.setText(intent.getStringExtra(Constant.LOGIN_PWD));
        }
        bundle = new Bundle();
        inputs = new AndroidNextInputs();
        perssionList = new ArrayList<>();
        inputs.add(userName, StaticScheme.Required().msgOnFail("手机号不能为空"),
                StaticScheme.ChineseMobile().msgOnFail("请输入正确的手机号码"));
        inputs.add(userPwd, StaticScheme.Required().msgOnFail("密码不能为空"));

        if (SPUtils.contains(context, Constant.LOGIN_NAME)) {
            userName.setText(String.valueOf(SPUtils.get(context, Constant.LOGIN_NAME, "")));
        }
        if (SPUtils.contains(context, Constant.LOGIN_PWD)) {
            userPwd.setText(Constant.PWD);
        }

    }

    @OnClick({R.id.forget_pwd, R.id.btn_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forget_pwd:
                //忘记密码
                bundle.putBoolean(Constant.CHANGE_PWD, false);
                intent.putExtras(bundle);
                intent.setClass(context, ChangePwdActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_login:
                goLogin();
                break;
        }
    }

    /**
     * 验证账号密码
     */
    private void goLogin() {
        boolean passed = inputs.test();
        if (passed) {
            showProgressDialog();
            //1、对是否记住密码进行了判断 如果有保存密码 则判断是否改动了密码框的初始化密码
            //2、如果核对密码框的密码与初始化密码相同则断定未进行更改密码 直接用本地的MD5密码进行验证登录
            //3、反之正常登录即可
            if (SPUtils.contains(context, Constant.LOGIN_PWD)) {
                if (Constant.PWD.equals(userPwd.getText().toString().trim())) {
                    mPresenter.setLogin(userName.getText().toString(), String.valueOf(SPUtils.get(context, Constant.LOGIN_PWD, "")), token);
                } else {
                    mPresenter.setLogin(userName.getText().toString(), MD5Utils.MD5(userPwd.getText().toString()), token);
                }
            } else {
                mPresenter.setLogin(userName.getText().toString(), MD5Utils.MD5(userPwd.getText().toString()), token);
            }
        } else {
            toast("请按提示填写");
        }
    }


    /**
     * @param userEntity 1为登录成功,2为用户名错误,3为密码错误
     */
    @Override
    public void setUserBack(User userEntity) {
        dissProgressDialog();
        int res = userEntity.getResStatus();
        //1、储存密码的时候会根据上面的验证逻辑进行是否转译的存储
        if (res == 1) {
            if (checkboxRem.isChecked()) {
                if (SPUtils.contains(context, Constant.LOGIN_PWD)) {
                    if (!Constant.PWD.equals(userPwd.getText().toString().trim())) {
                        //存储转译
                        SPUtils.put(context, Constant.LOGIN_NAME, userName.getText().toString().trim());
                        SPUtils.put(context, Constant.LOGIN_PWD, MD5Utils.md5(userPwd.getText().toString().trim()));
                    }
                } else {
                    //存储转译
                    SPUtils.put(context, Constant.LOGIN_NAME, userName.getText().toString().trim());
                    SPUtils.put(context, Constant.LOGIN_PWD, MD5Utils.md5(userPwd.getText().toString().trim()));
                }
            } else {
                if (SPUtils.contains(context, Constant.LOGIN_PWD)) {
                    SPUtils.remove(context, Constant.LOGIN_PWD);
                }
            }
            initPerssion(userEntity);
            XGPushManager.registerPush(context, userEntity.getLogonname());
            toast("登录成功");
            bundle.putSerializable(Constant.PERMISSION_LIST, (Serializable) perssionList);
            bundle.putSerializable(Constant.USER_ENTITY, userEntity);
            intent.setClass(context, MainActivity.class);
            startActivityMine(intent, bundle);
            finish();
        } else if (res == 2) {
            toast("用户名错误");
        } else if (res == 3) {
            toast("密码错误");
        }
    }

    /**
     * @param userEntity 初始化 角色的权限
     *                   目前为固定模式。待到以后动态获取时
     *                   直接把获取到的list添加到现有的list即可一切不变
     *                   1、超管
     *                   2、店长
     *                   3、财务
     *                   4、接单员
     *                   5、派送员
     *
     */
    private void initPerssion(User userEntity) {

        if (userEntity.getRoleid().equals("1")) {
            addData(PermissionConfig.MENU_FOOD_1, true, false);
            addData(PermissionConfig.MENU_RECEIVE_2, true, false);
            addData(PermissionConfig.MENU_MAKETING_4, true, false);
            addData(PermissionConfig.MENU_FINANCE_5, true, false);
            addData(PermissionConfig.MENU_VIP_6, true, false);
            addData(PermissionConfig.MENU_BUY_7, true, false);
            addData(PermissionConfig.MENU_STOREHOUSE_8, true, false);
            addData(PermissionConfig.MENU_SENDING_9, true, false);
            addData(PermissionConfig.MENU_DOSOMETHING_10, true, true);
            addData(PermissionConfig.MENU_MINE_11, true, true);
            addData(PermissionConfig.MENU_DATE_12, true, true);
            addData(PermissionConfig.MENU_ZONGWU_13, true, false);
            addData(PermissionConfig.MENU_XINZIBAO_14, true, true);

        } else if (userEntity.getRoleid().equals("2")) {
            addData(PermissionConfig.MENU_FOOD_1, true, true);
            addData(PermissionConfig.MENU_RECEIVE_2, true, false);
            addData(PermissionConfig.MENU_MAKETING_4, true, true);
            addData(PermissionConfig.MENU_FINANCE_5, true, false);
            addData(PermissionConfig.MENU_VIP_6, true, false);
            addData(PermissionConfig.MENU_BUY_7, true, true);
            addData(PermissionConfig.MENU_STOREHOUSE_8, true, true);
            addData(PermissionConfig.MENU_SENDING_9, true, false);
            addData(PermissionConfig.MENU_DOSOMETHING_10, true, true);
            addData(PermissionConfig.MENU_MINE_11, true, true);
            addData(PermissionConfig.MENU_DATE_12, true, false);
            addData(PermissionConfig.MENU_ZONGWU_13, true, true);
            addData(PermissionConfig.MENU_XINZIBAO_14, true, true);

        } else if (userEntity.getRoleid().equals("3")) {
            addData(PermissionConfig.MENU_FINANCE_5, true, true);
            addData(PermissionConfig.MENU_DOSOMETHING_10, true, true);
            addData(PermissionConfig.MENU_MINE_11, true, true);
            addData(PermissionConfig.MENU_XINZIBAO_14, true, true);
        } else if (userEntity.getRoleid().equals("4")) {
            addData(PermissionConfig.MENU_RECEIVE_2, true, true);
            addData(PermissionConfig.MENU_VIP_6, true, true);
            addData(PermissionConfig.MENU_DOSOMETHING_10, true, true);
            addData(PermissionConfig.MENU_MINE_11, true, true);
            addData(PermissionConfig.MENU_XINZIBAO_14, true, true);


        } else if (userEntity.getRoleid().equals("5")) {
            addData(PermissionConfig.MENU_SENDING_9, true, true);
            addData(PermissionConfig.MENU_DOSOMETHING_10, true, true);
            addData(PermissionConfig.MENU_MINE_11, true, true);
            addData(PermissionConfig.MENU_XINZIBAO_14, true, true);
        }

    }

}
